﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using AwesomeGame.Map;

namespace AwesomeGame.Weapons
{
    public class Bullet : IProjectile
    {
        public TimeSpan LastTeleport { get; set; }
        private float _rotation;
        public Vector2 Position { get; set; }
        private Texture2D _sprite;
        private Vector2 _spriteMidpoint;
        private TimeSpan _timeCreated = new TimeSpan();
        private float _movementSpeed = 4f;

        public delegate void BulletEvent(Bullet bullet);
        public event BulletEvent BulletExpired;
        public bool IsDeadly { get; set; }
        private Level _level;

        public Guid Id { get; set; }
        public long OwnerId { get; set; }

        public Bullet(Guid id, Vector2 startPosition, float rotation, long ownerId, ref Level level)
        {
            OwnerId = ownerId;
            IsDeadly = false;
            Id = id;
            _level = level;
            _rotation = rotation;
            Position = startPosition;
            _sprite = Game1.ContentManager.Load<Texture2D>(@"Weapons\Bullet");
            _spriteMidpoint = new Vector2(_sprite.Width / 2, _sprite.Height / 2);
        }

        public void Update(GameTime gameTime)
        {
            if (_timeCreated == new TimeSpan())
                _timeCreated = gameTime.TotalGameTime;
            if (gameTime.TotalGameTime - _timeCreated >= new TimeSpan(0, 0, 2))
                if (BulletExpired != null)
                    BulletExpired(this);
            if (IsDeadly == false &&  gameTime.TotalGameTime - _timeCreated >= new TimeSpan(0, 0, 0, 0, 300))
                IsDeadly = true;

            Vector2 newPosition = new Vector2();
            newPosition.X = (float)(Position.X + Math.Cos(_rotation) * _movementSpeed);
            newPosition.Y = (float)(Position.Y + Math.Sin(_rotation) * _movementSpeed);
            if (CanMoveToPosition(newPosition))
                Position = newPosition;
        }

        private bool CanMoveToPosition(Vector2 worldPosition)
        {
            TileTypes tile = _level.GetTileAtWorldPosition(worldPosition);
            if (tile == TileTypes.Floor)
                return true;

            return false;
        }

        public void Draw(GameTime gameTime)
        {
            Vector2 screenPosition = Camera.GetScreenPosition(Position);
            Game1.SpriteBatch.Draw(_sprite, screenPosition, null, Color.White, _rotation, _spriteMidpoint, 1f, SpriteEffects.None, 0.7f);
        }
    }
}
